package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.config.RedissonConfig;
import cn.itsource.ymcc.domain.KillActivity;
import cn.itsource.ymcc.domain.KillCourse;
import cn.itsource.ymcc.mapper.KillActivityMapper;
import cn.itsource.ymcc.service.IKillActivityService;
import cn.itsource.ymcc.service.IKillCourseService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.StrUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Eric Chen
 * @since 2022-07-28
 */
@Service
public class KillActivityServiceImpl extends ServiceImpl<KillActivityMapper, KillActivity> implements IKillActivityService {
    @Autowired
    private IKillCourseService killCourseService;
    @Autowired
    private RedisTemplate<Object , Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void publish(Long id) {
        //判断参数
        AssertUtil.isNotNull(id,"idnull");
        KillActivity killActivity = selectById(id);
        AssertUtil.isEquals(killActivity.getPublishStatus(),0,"活动不为未发布");

        //查询活动有的秒杀课程
        List<KillCourse> killCourses = killCourseService.selectByActiveId(id);
        if (killCourses.isEmpty())return;

        //存储redis
        Date date = new Date();
        killCourses.forEach(killCourse -> {
            //信号量存如redis
            RSemaphore semaphore = redissonClient.getSemaphore("store" + killCourse.getId());
            boolean b = semaphore.trySetPermits(killCourse.getKillCount());
//            AssertUtil.isTrue(b,"发布失败");
            if (b){
                //随机码
                killCourse.setKillCode(StrUtils.getComplexRandomString(6));
                redisTemplate.opsForHash().put("active:"+killCourse.getActivityId(),killCourse.getId().toString(),killCourse);
                killCourse.setPublishStatus(1);
                killCourse.setPublishTime(date);
                killCourseService.updateById(killCourse);

            } else {
                System.out.println("redis存储失败");
            }



        });

        //修改本地
        killActivity.setPublishStatus(1);
        killActivity.setCancelPublishTime(date);
        updateById(killActivity);

    }
}
